package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.comment.mapper.ApCommentMapper;
import com.heima.comment.pojo.ApComment;
import com.heima.comment.pojo.ApCommentDto;
import com.heima.comment.pojo.ApLikesDto;
import com.heima.comment.pojo.apPageDto;
import com.heima.comment.service.ApCommentService;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.BeanHelper;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.enums.CommentTypeEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-04-10
 */
@Service
public class ApCommentServiceImpl extends ServiceImpl<ApCommentMapper, ApComment> implements ApCommentService {

    private static Integer COMMENT_TYPE = 0;
    private static Integer LIKES = 1;

    @Override
    public void commentSave(CommentSaveDto dto) {
        // 判断当前用户登没登录
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId <= 0) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 赋值信息
        ApComment apComment = new ApComment();
        apComment.setArticleId(dto.getArticleId());
        apComment.setCommentUserId(userId);
        apComment.setCommentText(dto.getContent());
        apComment.setCreateTime(new Date());
        // 默认是主评论
        apComment.setType(COMMENT_TYPE);
        // 判断是否是粉丝
        // 昨天功能没落库，使用随机数函数模拟
        Random random = new Random();
        int nextInt = random.nextInt(2);
        if (nextInt == 0) {
            // 不是粉丝
            apComment.setIsFans(0);
        } else {
            // 是粉丝
            apComment.setIsFans(1);
        }
        this.save(apComment);
    }

    @Override
    public List<ApCommentDto> commentLoad(CommentDto dto) {
        LambdaQueryWrapper<ApComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(dto.getMinDate() != null, ApComment::getCreateTime, dto.getMinDate());
        // 只展示普通评论
        queryWrapper.eq(ApComment::getType, CommentTypeEnum.NORMAL.getValue());
        List<ApComment> list = this.list(queryWrapper);
        ArrayList<ApCommentDto> apCommentDtos = new ArrayList<>();
        for (ApComment apComment : list) {
            ApCommentDto apCommentDto = BeanHelper.copyProperties(apComment, ApCommentDto.class);
            apCommentDto.setContent(apComment.getCommentText());
            apCommentDtos.add(apCommentDto);
        }
        return apCommentDtos;
    }

    @Override
    public ApLikesDto commentLike(CommentLikeDto dto) {
        // 1、先判断登没登录
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId <= 0) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2、获取判断是点赞还是取消点赞 +1 -1
        Integer operation = dto.getOperation();
        // 3、根据评论id查询这条id当前总点赞量
        ApComment commentDB = this.getById(dto.getCommentId());
        if (operation.equals(LIKES)) {
            commentDB.setLikes(commentDB.getLikes() - LIKES);
        } else {
            commentDB.setLikes(commentDB.getLikes() + LIKES);
        }
        this.updateById(commentDB);
        // 3、返回总赞数
        ApLikesDto apLikesDto = new ApLikesDto();
        apLikesDto.setLikes(commentDB.getLikes());

        return apLikesDto;
    }
    @Override
    public PageResult getListPage(apPageDto dto) {
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null&&userId<=0){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        Page<ApComment> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApComment::getArticleId,dto.getArticleId());
        Page<ApComment> pageDB = this.page(page, queryWrapper);
        if(CollectionUtils.isEmpty(pageDB.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<ApComment> result = pageDB.getRecords().stream().map(apComment -> {
            apComment.setCreateTime(new Date());
            return apComment;
        }).collect(Collectors.toList());
        return new PageResult(dto.getPage(),dto.getSize(),pageDB.getTotal(),result);
    }
}
